package team.yidong.fenda.serviceImpl;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.yidong.fenda.entity.*;
import team.yidong.fenda.repository.*;
import team.yidong.fenda.service.QuestionService;

import javax.persistence.criteria.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * Created by xuanlong on 2017/10/27.
 */
@Service
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    QuestionRepository questionRepository;
    @Autowired
    WxOrderRepository wxOrderRepository;
    @Autowired
    QuestionURLRepository questionURLRepository;
    @Autowired
    AnswerRepository answerRepository;
    @Autowired
    AnswerImgRepository answerImgRepository;
    @Autowired
    MasterScoreRepository masterScoreRepository;

    @Override
    public JSONObject findQuestion(Integer hospitalId, String hospitalName, String userName, String isSolved, String haveImg, String questionClass, String askDate, String questionMoney, String maxDate, String questionContent, String answerStatus, Integer page, Integer page_size) {
        Pageable pageable = new PageRequest(page, page_size, Sort.Direction.DESC, "creatDate");
        Page<Question> questionPage = questionRepository.findAll(new Specification<Question>() {

            @Override
            public Predicate toPredicate(Root<Question> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (hospitalId != 1) {
                    Join<Question, User> join = root.join("user");
                    Join<Join, Hospital> join1 = join.join("hospital");
                    Predicate p = criteriaBuilder.equal(join1.get("id").as(Integer.class), hospitalId);
                    predicateList.add(p);
                }
                //查找不在黑名单中的用户的问题
              /*  if (true) {

                    Join<Question, User> join = root.join("user");
                    Predicate predicate = criteriaBuilder.notEqual(join.get("isBlack").as(String.class), "是");
                    predicateList.add(predicate);
                }*/
                Predicate p1 = criteriaBuilder.notEqual(root.get("status").as(String.class), "black");
                predicateList.add(p1);
                if (hospitalName != null && !hospitalName.equals("")) {
                    Join<Question, User> join = root.join("user");
                    Join<Join, Hospital> join1 = join.join("hospital");
                    Predicate p = criteriaBuilder.equal(join1.get("name").as(String.class), hospitalName);
                    predicateList.add(p);
                }
                if (userName != null && !userName.equals("")) {
                    Join<Question, User> join = root.join("user");
                    Predicate p = criteriaBuilder.like(join.get("name").as(String.class), "%" + userName + "%");
                    predicateList.add(p);
                }
                if (questionContent != null && !questionContent.equals("")) {
                    System.out.println(questionContent);
                    Predicate p = criteriaBuilder.like(root.get("info").as(String.class), "%" + questionContent + "%");
                    predicateList.add(p);
                }
                if (isSolved != null && !isSolved.equals("")) {

                    Predicate p = criteriaBuilder.equal(root.get("isSolved").as(String.class), isSolved);
                    predicateList.add(p);
                }
                if ("有".equals(haveImg)) {

                    Predicate p = criteriaBuilder.isNotEmpty(root.get("questionURLSet"));
                    predicateList.add(p);
                }
                if ("无".equals(haveImg)) {
                    Predicate p = criteriaBuilder.isEmpty(root.get("questionURLSet"));
                    predicateList.add(p);
                }
                if ("是".equals(answerStatus)) {
                    Predicate p = criteriaBuilder.equal(root.get("answerStatus"), "过期无法回答");
                    predicateList.add(p);
                }
                if ("否".equals(answerStatus)) {
                    Predicate p = criteriaBuilder.equal(root.get("answerStatus"), "可回答");
                    predicateList.add(p);
                }
                if (questionClass != null && !questionClass.equals("")) {

                    Predicate p = criteriaBuilder.like(root.get("questionClass").as(String.class), "%" + questionClass + "%");
                    predicateList.add(p);
                }
                if (askDate != null && !askDate.equals("")) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date creatDate = simpleDateFormat.parse(askDate);
                        Predicate p = criteriaBuilder.greaterThanOrEqualTo(root.get("creatDate").as(Date.class), creatDate);
                        predicateList.add(p);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (maxDate != null && !maxDate.equals("")) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date creatDate = simpleDateFormat.parse(maxDate);
                        Predicate p = criteriaBuilder.lessThanOrEqualTo(root.get("creatDate").as(Date.class), creatDate);
                        predicateList.add(p);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (questionMoney != null && !questionMoney.equals("")) {
                    Join<Question, WxOrder> join = root.join("wxOrder");
                    Predicate p = criteriaBuilder.equal(join.get("money").as(Integer.class), questionMoney);
                    predicateList.add(p);
                }
                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        }, pageable);
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[]{"hospitalPermissionSet", "masterScoreSet", "question", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList", " masterScore", "orderMoneyToList", "orderQuestion", "masterAnswerList"});
        JSONObject jsonObject = JSONObject.fromObject(questionPage, jsonConfig);
        String temp = "{\"total\":" + jsonObject.getString("totalElements") + ",\"rows\":" + jsonObject.getString("content") + "}";
        JSONObject j = JSONObject.fromObject(temp);
        return j;

    }


    @Override
    public List<Question> findLatestQuestionByHospital(Integer hospitalId) {
        return questionRepository.findLatestQuestionByHospital(hospitalId, new Sort(Sort.Direction.DESC, "creatDate"));
    }

    @Override
    public JSONObject questionInfo(Integer questionId) {
        Question question = questionRepository.findOne(questionId);
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[]{"hospitalPermissionSet", "masterScoreSet", "question", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList", "orderMoneyToList", "orderQuestion", "masterAnswerList", "masterScoreAnswer"});
        JSONObject jsonObject = JSONObject.fromObject(question, jsonConfig);
        return jsonObject;
    }

    @Override
    public List<String> findQuestionClassByHospital(Integer hospitalId) {
        if (hospitalId != 1) {
            return questionRepository.findQuestionClassByHospital(hospitalId);
        } else {
            return questionRepository.findAllQuestionClass();
        }

    }


    @Override
    public void deleteQuestion(Integer questionId) {
      /*  WxOrder wxOrder = wxOrderRepository.findByQuestionId(questionId);
        System.out.println(wxOrder.getId());
        wxOrderRepository.delete(wxOrder);
        List<Answer> answerList = answerRepository.findAnswerByQuestionId(questionId);
        for (Answer answer : answerList) {
            Set<AnswerImg> answerImgSet = answer.getAnswerImgSet();
            answerImgRepository.delete(answerImgSet);
            System.out.println(1);
            MasterScore masterScore = answer.getMasterScore();
            masterScoreRepository.delete(masterScore);
            System.out.println(2);
        }



        questionURLRepository.delete(question.getQuestionURLSet());
        System.out.println(4);*/
        Question question = questionRepository.findOne(questionId);
        questionRepository.delete(question);

    }
}
